<template>
  <div>
    <video ref="video" width="320" height="240" autoplay class="sxt"></video>
    <div class="div-bao">
      <button @click="takePicture" v-if="videoPlaying" class="bao">保存照片</button>
    </div>
    <div class="div-open">
      <button @click="openCamera" class="open">打开摄像头</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      videoPlaying: false
    };
  },
  methods: {
    openCamera() {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true })
          .then(stream => {
            this.$refs.video.srcObject = stream;
            this.videoPlaying = true;
          })
          .catch(error => {
            console.error('无法打开摄像头', error);
          });
      } else {
        console.error('浏览器不支持摄像头API');
      }
    },
    takePicture() {
      const canvas = document.createElement('canvas');
      canvas.width = this.$refs.video.videoWidth;
      canvas.height = this.$refs.video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(this.$refs.video, 0, 0, canvas.width, canvas.height);
      const img = document.createElement('img');
      img.src = canvas.toDataURL('image/png');
      // 在这里你可以将图片上传到服务器或保存到本地
    }
  }
};
</script>
<style scoped>
.sxt{
  width: 100%;
  height: 564px;
}
/* .div-bao{
  width: 25%;
  height: 180px;
  background-color: #000;
  position: relative;
  border-radius: 50%;
  margin-left: 285px;
  margin-top: 20px;
} */
.bao{
  /* width: 80%; */
  /* height: 80%; */
  /* margin: 10%; */
  width: 25%;
  height: 180px;
  margin-left: 37.5%;
  background-color: #000;
  color: #fff;
  border-radius: 50%;
  /* position: absolute; */
}
.div-open{
  width: 25%;
  height: 180px;
  background-color: #000;
  position: relative;
  border-radius: 50%;
  margin-left: 285px;
  margin-top: 20px;
}
.open{
  width: 80%;
  height: 80%;
  border: 1px solid #ccc;
  border-radius: 50%;
  background-color: #fff;
  /* position: fixed; */
  position: absolute;
  margin: 10%;
}
</style>
